
var layer = layui.layer //弹层
    ,table = layui.table //表格
    form = layui.form,$ = layui.jquery,changeList=[],laydate = layui.laydate;
lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});

function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        tmparr["selected"]=true;
        if(item["users"]){
            for(let it of item["users"]){
                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}

function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,

        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            return this
        }
    })
}
let operationList=[];
(function () {
    //获取当前用户的部门及人员结构树
    let treeList = getCurrentDepartmentUser();

    if(treeList && treeList.list){
        let userTree = getAllJson(treeList.list);
        operationList=getxmselect("#operationCode","operationCode", userTree);
    }else {
        operationList=getxmselect("#operationCode","operationCode", [{name: user.name, value: user.code}]);
    }

})()

let initData = [];
table.render({
    elem: '#offer'
    ,data:initData
    ,url:"resourceSamples/import/getPurchaseSampleInfoByPage"
    ,where:{operationCode:operationList.getValue('valueStr')}
    ,cols: [[
        {checkbox: true, fixed: true,title:'选择'},
        {field:'purchaseNo', title: '采购合同号'},
        {field:'supplierName', title:'供应商'},
        {field:'currency', title:'币种'},
        {field:'salesmanName', title:'业务员'},
        {field:'operationName', title:'操作员'}
    ]]
    ,id: 'offertableid'
    ,height: 300
    ,page: true
    ,done: function (res, curr, count) {
        table.render({
            elem: '#offerproduct'
            ,url:"resourceSamples/import/getPurchaseSampleProductById"
            ,cols: [[
                {checkbox: true, sort : true,title:'选择'},
                {field:'productCode', title:'产品编码', sort : true},
                {field:'specificationCode', title:'规格编码', sort : true},
                {field:'specificationExplanation', title:'规格说明', sort : true},
                {field:'productCname', title:'中文名称', sort : true},
                {field:'productEname', title:'英文名称', sort : true},
                {field:'productCdesc', title:'中文描述', sort : true},
                {field:'productEdesc', title:'英文描述', sort : true},
                {field:'unitPrice', title:'单价', sort : true},
                {field:'num', title:'数量', sort : true},
                {field:'productNum', title:'剩余数量', sort : true},
                {field:'productUnit', title:'单位', sort : true}
            ]]
            ,id: 'offerproducttableid'
            ,where: {
                id:res.data.length == 0 ? "":res.data[0].id
            }
            ,height: 400
            ,done:function () {
                $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
            }
        });

    }
});

//监听主表复选框
table.on('checkbox(offertable)', function (data) {
    let id = data.data.id;
    table.reload('offerproducttableid', {
        page: {
            limit: 10,
            curr: 1 //重新从第 1 页开始
        }
        ,where: {
            id:id
        },
        done: function (res, curr, count) {
            let child = $("#offerproduct").next().find('tbody input[type="checkbox"]');
            child.each(function(index, item){
                item.checked = data.checked;
            });
            if(data.checked){
                for(var i = 0; i < res.data.length; i++){
                    changeList.push(res.data[i]);
                }
            }else{
                if(changeList.length > 0){
                    for(var i = 0; i < res.data.length; i++){
                        deleteData(res.data[i]);
                    }
                }
            }
            form.render('checkbox');

            $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
        }
    }, 'data');
});

function deleteData(data){
    let id = data.id;
    let parentId = data.parentId;
    for(var j = 0; j < changeList.length; j++){
        if (changeList[j].id == id && changeList[j].parentId == parentId) {
            changeList.splice(j, 1); // 将使后面的元素依次前移，数组长度减1
            j--; // 如果不减，将漏掉一个元素
        }
    }
}

//监听子复选框
table.on('checkbox(offerproducttable)', function (obj) {
    if (obj.checked) {
        changeList.push(obj.data);
    } else {
        for (let index in changeList) {
            if (changeList[index].id == obj.data.id && changeList[index].parentId == obj.data.parentId) {
                changeList.splice(index,1);
            }
        }
    }
    form.render('checkbox');
});


//单击行事件
table.on('row(offertable)', function (obj) {
    let id = obj.data.id;
    table.reload('offerproducttableid', {
        page: {
            limit: 10,
            curr: 1 //重新从第 1 页开始
        }
        ,where: {
            id:id
        },
        parseData: function (res) {
            if (changeList) {
                for (let i in res.data) {
                    for (let j in changeList) {
                        if (changeList[j].id == res.data[i].id &&  changeList[j].parentId == res.data[i].parentId) {
                            res.data[i].LAY_CHECKED = 'true';
                        }
                    }
                }
            }
            return res;
        },
        done: function (res, curr, count) {
            $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
        }
    }, 'data');

});


form.on('submit(submitform)', function(data){
    table.reload('offertableid', {
        page: {
            limit:10,
            curr: 1 //重新从第 1 页开始
        }
        ,where: data.field
    }, 'data');
    return false;
});


$("#choose").on("click",function () {

    if(changeList.length == 0){
        layer.msg("请选择数据")
    }else{
        //产品明细数据
        let oldData =  parent.table.cache["productinformationtableid"];
        $.each(changeList, function (index, value) {
            //剔除重复数据
            let flag = true;
            if(oldData.length > 0){
                for(var i = 0; i < oldData.length; i++){
                    let sameFlag = oldData[i]["sameId"] != "undefined" && oldData[i]["sameId"] == changeList[index].id;
                    if(sameFlag){
                        flag = false;
                        break;
                    }
                }
            }
            if(flag){
                //不存在重复数据,添加数据
                //1.产品
                let tempData = changeList[index];
                tempData["tempId"] = GenNonDuplicateID(3) + (index+1)
                tempData["sameId"] = tempData.id;
                tempData["lotNo"] = tempData.purchaseNo;
                tempData["id"] = null;
                oldData.push(tempData);
            }

        });

        //重载产品明细表单
        parent.table.reload('productinformationtableid', {data:oldData, limit:oldData.length});

        //执行接口
        layer.msg("保存成功", {icon: 6});
        setTimeout(function () {
            //保存成功则关闭此页面
            let index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        },)
    }
})


$("#shutdown").on("click",function () {
    let index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
})

//生成临时id
function GenNonDuplicateID(randomLength){
    return Number(Math.random().toString().substr(3,randomLength) + Date.now()).toString(36)
}

//时间处理 获取当前时间type:1 yyyy-MM-dd type:2 yyyyMMdd+毫秒
function getNowFormatDate(type) {
    let date = new Date();
    let separator = "-";
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if(1 == type){
        let currentDate = year + separator + month + separator + strDate;
        return currentDate;
    }else if(2 == type){
        let second = date.getMilliseconds().toString();
        if(second.length < 3){
            if(second.length == 1){
                second = "0" + "0" + second;
            }else {
                second = "0" + second;
            }
        }
        let currentDate = year.toString() + month.toString() + strDate.toString() + second;
        return currentDate;
    }

}

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}

let currentDate = getNowFormatDate(1);

document.getElementById('clear').onclick = function(){
    operationNoList.setValue([ ]);
};